# make us_server
# author Colocasia

CC ?= gcc
CFLAGS = -g -O2 -Wall -I$(LUA_INC)

.PHONY: all skynet tools 
UNAME ?= $(shell uname)
THIRD_LIB_ROOT ?= ./libs

# prefix
PREFIX_USER ?= /usr/local

# skynet
SKYNET_ROOT ?= $(THIRD_LIB_ROOT)/skynet

# lua
LUA_VER ?= 5.3
LUA_INC ?= $(SKYNET_ROOT)/3rd/lua

# C-Service
CSERVICE =
CSERVICE_PATH ?= server/cservice

# C-LuaLib
LUA_CLIB = mylualib cjson us luasocket
LUA_CLIB_PATH ?= server/luaclib


# lua-cjson
CJSON_ROOT ?= $(THIRD_LIB_ROOT)/lua-cjson
# lua-socket
LUA_SOCKET_ROOT ?= $(THIRD_LIB_ROOT)/lua-socket


# C-LuaTool
LUA_CTOOL = luasql
LUA_CTOOL_PATH ?= tools
LUA_CTOOL_INC ?= $(PREFIX_USER)/include/lua$(LUA_VER)
LUA_CTOOL_CDIR ?= $(PREFIX_USER)/lib/lua/$(LUA_VER)
LUA_CTOOL_LDIR ?= $(PREFIX_USER)/share/lua/$(LUA_VER)
.PHONY: $(LUA_CTOOL)


ifeq ($(UNAME), Darwin)		
# mac
PLAT ?= macosx
SHARED ?= -fPIC -dynamiclib -Wl,-undefined,dynamic_lookup
# make skynet
SKYNET_MAKE_CMD = make -C $(SKYNET_ROOT) macosx
else
# other
PLAT ?= linux
SHARED := -fPIC --shared
# make skynet
SKYNET_MAKE_CMD = make -C $(SKYNET_ROOT) linux
endif

all : skynet \
	$(foreach v, $(CSERVICE), $(CSERVICE_PATH)/$(v).so) \
  	$(foreach v, $(LUA_CLIB), $(LUA_CLIB_PATH)/$(v).so) \
	tools

skynet :
	$(SKYNET_MAKE_CMD)

tools:
	$(MAKE) $(foreach v, $(LUA_CTOOL), $(v))


# C服务
$(CSERVICE_PATH) :
	mkdir -p $(CSERVICE_PATH)

# Lua扩展库
$(LUA_CLIB_PATH) :
	mkdir -p $(LUA_CLIB_PATH)

$(LUA_CLIB_PATH)/mylualib.so : $(THIRD_LIB_ROOT)/mylualib/mylualib.c | $(LUA_CLIB_PATH)
	$(CC) $(CFLAGS) $(SHARED) $^ -o $@ 

$(LUA_CLIB_PATH)/us.so : $(THIRD_LIB_ROOT)/us-core/us_core.c | $(LUA_CLIB_PATH)
	$(CC) $(CFLAGS) $(SHARED) $^ -o $@ 

$(LUA_CLIB_PATH)/cjson.so : $(LUA_CLIB_PATH)
	cd $(CJSON_ROOT) \
	&& $(MAKE) LUA_INCLUDE_DIR=../../$(LUA_INC) CC=$(CC) CJSON_LDFLAGS="$(SHARED)" \
	&& cd - \
	&& cp $(CJSON_ROOT)/cjson.so $@

$(LUA_CLIB_PATH)/luasocket.so : $(LUA_CLIB_PATH)
	cd $(LUA_SOCKET_ROOT) \
	&& $(MAKE) $(PLAT) LUAV=$(LUA_VER) LUAINC_macosx=../../../$(LUA_INC) prefix=/usr/local \
	&& sudo $(MAKE) install LUAV=$(LUA_VER) prefix=/usr/local \
	&& cp src/socket-3.0-rc1.so ../../server/luaclib/socket.so \
	&& cd - $@

# Lua工具库
luasql :
	cd $(LUA_CTOOL_PATH)/lua-sql \
	&& $(MAKE) postgres && sudo $(MAKE) install \
	&& cd - $@

clean :
	rm -f $(CSERVICE_PATH)/*.so $(LUA_CLIB_PATH)/*.so
	make -C $(SKYNET_ROOT) clean
	make -C $(LUA_SOCKET_ROOT) clean

cleanall: clean
	make -C $(SKYNET_ROOT) cleanall
